package com.example.springboot.util;

import lombok.Data;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.UUID;

@Data
public class ImageCode {

    private BufferedImage image;

    private String code;

    private LocalDateTime expireTime;

    public ImageCode(BufferedImage image,String code,int expireIn){
        this.image = image;
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
    }

    public static ImageCode createImage(){
        //设置字体样式
        Font font = new Font("宋体", Font.PLAIN, 25);
        //图片大小
        int width = 1000;
        int height = 1000;

        //创建一个图片缓冲区
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        //获取图片处理对象
        Graphics graphics = image.getGraphics();
        //填充背景色
        graphics.setColor(getRandomColor());
        graphics.fillRect(1, 1, width - 1, height - 1);
        //设定边框颜色
        graphics.setColor(getRandomColor());
        graphics.drawRect(0, 0, width - 1, height - 1);
        //设置干扰线
        graphics.setColor(getRandomColor());
        Random random = new Random();
        for(int i=0;i<20;i++){
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int x1 = random.nextInt(width - 1);
            int y1 = random.nextInt(height - 1);
            graphics.drawLine(x, y, x1, y1);
        }
        //写入文字
        graphics.setColor(getRandomColor());
        graphics.setFont(font);
        String content = UUID.randomUUID().toString().replace("-","").substring(0,4);
        graphics.drawString(content, 100, 100);
        //释放资源
        graphics.dispose();
        return new ImageCode(image,content,60);

    }

    /**
     * 获取随机颜色
     * @return
     */
    public static Color getRandomColor() {
        Random random = new Random();
        int r = random.nextInt(255);
        int g = random.nextInt(255);
        int b = random.nextInt(255);
        return new Color(r, g, b);
    }

}
